package ltd.controller;

import com.googlecode.genericdao.search.Search;
import ltd.entity.Simulator;
import ltd.service.SimulatorService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@Controller
public class HelloWorldController {
    @Resource(name = "simulatorService")  // 获取applicationContext.xml中bean的id为simulatorService的，并注入
    private SimulatorService simulatorService ;//等价于spring传统注入方式写get和set方法，这样的好处是简洁工整，省去了不必要得代码

    @ModelAttribute
    @RequestMapping("/hello1")
    public ModelAndView helloWorld(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String message = "Hello World, Spring 3.0!";
        System.out.println(message);

//        gamesConfigService = (SimulatorService) SpringContextUtil.getBean("gamesConfigService");
        Search search = new Search(Simulator.class);
        search.addFilterEqual("type", 691);
        int count = simulatorService.count(search);
        System.out.println("count:" + count);
        return new ModelAndView("hello", "message", message);
    }

    @Resource
    SessionFactory sessionFactory;

    @ModelAttribute
    @RequestMapping("/hello")
    public void hello(HttpServletResponse response) throws IOException {
        Session session = sessionFactory.openSession();
        List list =  session.createSQLQuery( " select * from  " + "simulator" ).addEntity(Simulator. class ).list();
        Iterator it = list.iterator();
        while(it.hasNext()) {
            System.out.println(it.next());
        }
        session.close();
//        String message = "Hello World, Spring 3.0!";
//        System.out.println(message);
//        Person person = new Person("chinalin",21,"男") ;
//
//        response.setContentType("application/json");
//        response.setCharacterEncoding("UTF-8");
//        PrintWriter writer = response.getWriter() ;
//        String json = JsonUtil.toJson(person) ;
//        writer.write(json);
//        writer.flush();
//        writer.close();
    }
}